﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;



public class OrderDetails
{
    public string ProductName { get; set; }
    public decimal Quantity { get; set; }
    public decimal Price { get; set; }//这是单价

    public override bool Equals(object obj)
    {
        if (obj is OrderDetails other)
        {
            return ProductName == other.ProductName && Quantity == other.Quantity && Price == other.Price;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(ProductName, Quantity, Price);
    }

    public override string ToString()
    {
        return $"Product: {ProductName}, Quantity: {Quantity}, Price: {Price}";
    }
}

public class Order
{
    public int OrderId { get; set; }
    public string Customer { get; set; }
    public List<OrderDetails> Details { get; set; } = new List<OrderDetails>();
    // 单独字段存储数据库值,原本定义无法写入
    public string _dbDetailsSummary;
    public decimal _dbTotalAmount;

    public string DetailsSummary => _dbDetailsSummary ?? (Details.Any() ?
        string.Join(", ", Details.Select(d => $"{d.ProductName}(×{d.Quantity})")) :
        "无商品");

    public decimal TotalAmount => _dbTotalAmount != 0 ? _dbTotalAmount : Details.Sum(d => d.Quantity * d.Price);

    public override bool Equals(object obj)
    {
        if (obj is Order other)
        {
            return OrderId == other.OrderId && Customer == other.Customer && Details.SequenceEqual(other.Details);
        }
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(OrderId, Customer, Details);
    }

    public override string ToString()
    {
        return $"Order ID: {OrderId}, Customer: {Customer}, Total Amount: {TotalAmount}\n\nDetails:\n{string.Join("\n", Details)}";
    }
}

public class OrderService
{
    private List<Order> orders = new List<Order>();

    public void AddOrder(Order order)
    {
        if (orders.Any(o => o.OrderId == order.OrderId))
        {
            throw new InvalidOperationException("Order with the same ID already exists.");
        }
        orders.Add(order);
    }

    public void RemoveOrder(int orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new InvalidOperationException("Order not found.");
        }
        orders.Remove(order);
    }

    public void UpdateOrder(Order order)
    {
        var existingOrder = orders.FirstOrDefault(o => o.OrderId == order.OrderId);
        if (existingOrder == null)
        {
            throw new InvalidOperationException("Order not found.");
        }
        orders.Remove(existingOrder);
        orders.Add(order);
    }

    public List<Order> QueryOrders(OrderQueryParameters parameters)
    {
        var orders = new List<Order>();
        string constring = "data source=localhost;database=dingdan;user id=root;password=asdfg123456;pooling=true;charset=utf8;";
        using (var connection = new MySqlConnection(constring))
        {
            connection.Open();

            // 构建 SQL 查询
            var sql = new StringBuilder(@"
            SELECT o.order_id, o.customer, o.totalAmount, o.detailsSummary,
                   d.product_name, d.quantity, d.price
            FROM orders o
            LEFT JOIN order_details d ON o.order_id = d.order_id
            WHERE 1=1");

            var command = new MySqlCommand(sql.ToString(), connection);

            if (parameters.OrderId.HasValue)
            {
                sql.Append(" AND o.order_id = @OrderId");
                command.Parameters.AddWithValue("@OrderId", parameters.OrderId.Value);
            }

            if (!string.IsNullOrEmpty(parameters.Customer))
            {
                sql.Append(" AND o.customer LIKE @Customer");
                command.Parameters.AddWithValue("@Customer", $"%{parameters.Customer}%");
            }

            if (parameters.MinAmount.HasValue)
            {
                sql.Append(" AND o.totalamount >= @MinAmount");
                command.Parameters.AddWithValue("@MinAmount", parameters.MinAmount.Value);
            }

            if (parameters.MaxAmount.HasValue)
            {
                sql.Append(" AND o.totalamount <= @MaxAmount");
                command.Parameters.AddWithValue("@MaxAmount", parameters.MaxAmount.Value);
            }

            command.CommandText = sql.ToString();

            // 执行查询
            using (var reader = command.ExecuteReader())
            {
                var orderDict = new Dictionary<int, Order>();

                while (reader.Read())
                {
                    int orderId = reader.GetInt32("order_id");

                    if (!orderDict.ContainsKey(orderId))
                    {
                        var order = new Order
                        {
                            OrderId = orderId,
                            Customer = reader.GetString("customer"),
                        };
                        orderDict[orderId] = order;
                        orders.Add(order);
                    }

                    if (!reader.IsDBNull(reader.GetOrdinal("product_name")))
                    {
                        var detail = new OrderDetails
                        {
                            ProductName = reader.GetString("product_name"),
                            Quantity = reader.GetInt32("quantity"),
                            Price = reader.GetDecimal("price")
                        };
                        orderDict[orderId].Details.Add(detail);
                    }
                }
            }
        }

        return orders;
    }
    public class OrderQueryParameters
    {
        public int? OrderId { get; set; }
        public string Customer { get; set; }
        public decimal? MinAmount { get; set; }
        public decimal? MaxAmount { get; set; }

        public override string ToString()
        {
            var conditions = new List<string>();

            if (OrderId.HasValue)
                conditions.Add($"订单ID: {OrderId}");

            if (!string.IsNullOrEmpty(Customer))
                conditions.Add($"客户名称: {Customer}");

            if (MinAmount.HasValue || MaxAmount.HasValue)
            {
                var range = MinAmount.HasValue ? $"≥{MinAmount}" : "";
                range += MaxAmount.HasValue ? $"≤{MaxAmount}" : "";
                conditions.Add($"金额范围: {range}");
            }

            return conditions.Any()
                ? "当前搜索条件:\n" + string.Join("\n", conditions)
                : "当前无搜索条件";
        }
    }

    public List<Order> GetAllOrders()
    {
        var orders = new List<Order>();
        string constring = "data source=localhost;database=dingdan;user id=root;password=asdfg123456;pooling=true;charset=utf8;";
        using (var connection = new MySqlConnection(constring))
        {
            connection.Open();
            string sql = "SELECT * FROM orders";
            using (var command = new MySqlCommand(sql, connection))
            {
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var order = new Order
                        {
                            OrderId = reader.GetInt32("order_id"),
                            Customer = reader.GetString("customer"),

                            _dbTotalAmount = reader.GetDecimal("totalAmount"),
                            _dbDetailsSummary = reader.GetString("detailsSummary"),

                            // 其他字段
                        };
                        orders.Add(order);
                    }
                }
            }
        }
        return orders;
    }

    public void SortOrders(Comparison<Order> comparison = null)//默认是null，按照ID排序，可以自定义排序方法
    {
        if (comparison == null)
        {
            orders.Sort((o1, o2) => o1.OrderId.CompareTo(o2.OrderId));
        }
        else
        {
            orders.Sort(comparison);
        }
    }
}